<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" type="text/css" href="https://www.layuicdn.com/layui-v2.6.2/css/layui.css"/>
</head>
<body>
<div id="car-type-form" class="layui-hide">
  <form class="layui-form" id="carType-form-layui">
    <div id="id-item" class="layui-form-item">
      <label class="layui-form-label">id</label>
      <div class="layui-input-inline">
        <input type="text" name="id" id="id" readonly autocomplete="off" class="layui-input"/>
      </div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">名称</label>
      <div class="layui-input-inline">
        <input type="text" name="name" placeholder="请输入类型名称" required lay-filter="required" id="name" autocomplete="off"
               class="layui-input"/>
      </div>
    </div>

    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">备注</label>
      <div class="layui-input-inline">
                <textarea type="text" name="remake" id="remake" placeholder="请输入备注" autocomplete="off"
                          class="layui-textarea"></textarea>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button id="insert" class="layui-btn" lay-submit lay-filter="insert">立即提交</button>
        <button id="update" class="layui-btn" lay-submit lay-filter="update">立即提交</button>
        <button id="reset" type="reset" class="layui-btn layui-btn-primary">重置</button>
      </div>
    </div>
  </form>
</div>
<div class="layui-form">
  类型名称：
  <div class="layui-inline">
    <input class="layui-input" name="name" autocomplete="off">
  </div>
  <button class="layui-btn" lay-filter="search" lay-submit>搜索</button>
</div>
<table class="layui-hide" id="car-type" lay-filter="car-type"></table>
<script type="text/html" id="leftBtn">
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>


<script src="https://www.layuicdn.com/layui-v2.6.2/layui.js"></script>
<script th:inline="none" type="text/javascript">
  layui.use(['table', 'layer', 'form'], function () {
    const table = layui.table;
    const form = layui.form;
    const layer = layui.layer;
    const $ = layui.$;
    const tableIns = table.render({
      id: 'car-type-table',
      elem: '#car-type',
      url: "/car-type/page",
      contentType: 'application/json',
      method: 'post', //异步请求方法
      toolbar: 'default',
      title: '汽车类型表',
      cols: [[
        {type: 'checkbox', fixed: 'left'},
        {field: 'id', title: 'id', width: 70},
        {field: 'name', title: '类型名'},
        {field: 'remake', title: '描述'},
        {fixed: 'right', title: '操作', toolbar: '#leftBtn', width: 200}
      ]],
      page: true
      , response: {
        statusCode: 200 //重新规定成功的状态码为 200，table 组件默认为 0
      }
      , request: {
        pageName: 'pageNum' //页码的参数名称，默认：page
        , limitName: 'pageSize' //每页数据量的参数名，默认：limit
      }
      , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
        console.log(res);
        return {
          "code": res.code, //解析接口状态
          "msg": res.message, //解析提示文本
          "count": res.map.data.total, //解析数据长度
          "data": res.map.data.records//解析数据列表
        };
      }
    });

    // 重载
    form.on("submit(search)", data => {
      tableIns.reload({
        url: "/car-type/page",
        contentType: 'application/json',
        method: 'post',
        where: data.field,
        page: {
          pageNum: 1 // 重新从第 1 页开始
        }
      });
    })

    form.on('submit(insert)', (data) => {
      const params = JSON.stringify(data.field);
      console.log(params);
      const loadIndex = layer.load(2);
      $.ajax({
        'contentType': 'application/json;charset=utf-8',
        'data': params,
        'url': 'car-type',
        'type': 'post',
        success: function (data) {
          if (data.code && data.code === 200) {
            layer.msg('添加成功');
            setTimeout(() => {
              layer.closeAll();
              table.reload('car-type-table', {}, true);
            }, 1000)
          } else {
            layer.close(loadIndex);
            layer.msg(data.message);
          }
        }
      });
      return false;
    })

    form.on('submit(update)', (data) => {
      const id = data.field.id;
      const params = JSON.stringify(data.field);
      const loadIndex = layer.load(2);
      $.ajax({
        'contentType': 'application/json;charset=utf-8',
        'data': params,
        'url': 'car-type/' + id,
        'type': 'put',
        success: function (data) {
          if (data.code && data.code === 200) {
            layer.msg('修改成功');
            setTimeout(() => {
              layer.closeAll();
              table.reload('car-type-table', {}, true);
            }, 1000)
          } else {
            layer.close(loadIndex);
            layer.msg(data.message);
          }
        }
      });

      return false;
    })
    table.on("tool(car-type)", (obj) => {
      const data = obj.data; //获得当前行数据
      const layEvent = obj.event;
      console.log(data);
      if (layEvent === 'del') { //删除
        layer.confirm('真的删除行么', function (index) {
          layer.close(index);
          //向服务端发送删除指令
          const loadIndex = layer.load(2);
          $.ajax({
            'url': 'car-type/' + data.id,
            'type': 'delete',
            success: function (data) {
              if (data.code && data.code === 200) {
                setTimeout(() => {
                  layer.closeAll();
                  table.reload('car-type-table');
                }, 1000)
              } else {
                layer.close(loadIndex);
                layer.msg(data.message);
              }
            }
          });
        });
      } else if (layEvent === 'edit') { //编辑
        layer.open({
          title: '修改汽车类型',
          type: 1,
          skin: 'layui-layer-rim', //加上边框
          area: ['400px', '400px'], //宽高
          offset: 'auto',
          closeBtn: 1,
          content: $("#car-type-form").html(),
          success: function (layero) {
            form.render();
            layero.find('#insert').hide();
            layero.find('#reset').hide();
            layero.find('#id').val(data.id);
            layero.find('#name').val(data.name);
            layero.find('#remake').val(data.remake);

          },
        });
      }
    })
    table.on("toolbar(car-type)", (obj) => {
      let checkStatus = table.checkStatus(obj.config.id).data;
      switch (obj.event) {
        case 'add':
          // 打开添加弹出层
          layer.open({
            title: '添加汽车类型',
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: ['400px', '300px'], //宽高
            offset: 'auto',
            closeBtn: 1,
            content: $("#car-type-form").html(),
            success: function (layero) {
              form.render();
              layero.find('#update').hide();
              layero.find('#id-item').hide();
            },
          });
          break;
        case 'delete':
          let params = '';
          for (let i = 0; i < checkStatus.length; i++) {
            params += "&id=" + checkStatus[i].id;
          }
          params = params.substr(1)
          console.log(params);
          const loadIndex = layer.load(2);
          $.ajax({
            'data': params,
            'url': 'car-type',
            'type': 'delete',
            success: function (data) {
              if (data.code && data.code === 200) {
                layer.msg('删除成功');
                setTimeout(() => {
                  layer.closeAll();
                  table.reload('car-type-table');
                }, 1000)
              } else {
                layer.close(loadIndex);
                layer.msg(data.message);
              }
            }
          });

          break;
        case 'update':
          if (checkStatus.length == 1) {
            layer.open({
              title: '修改汽车类型',
              type: 1,
              skin: 'layui-layer-rim', //加上边框
              area: ['400px', '400px'], //宽高
              offset: 'auto',
              closeBtn: 1,
              content: $("#car-type-form").html(),
              success: function (layero) {
                form.render();
                layero.find('#insert').hide();
                layero.find('#reset').hide();
                const data = checkStatus[0];
                layero.find('#id').val(data.id);
                layero.find('#name').val(data.name);
                layero.find('#remake').val(data.remake);

              },
            });
          } else if (checkStatus.length === 0) {
            layer.msg('请选择一个要编辑的行');
          } else {
            layer.msg('您只能选择一行');
          }
          break;
      }
      ;
    })
  });
</script>
</body>
</html>